package org.xydpeng.framework.l2cache.message;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.xydpeng.framework.l2cache.properties.L2CacheConfigProperties;

import java.util.Objects;

/**
 * @author xydpeng
 * @version v1.0
 * @date: 2024/6/7
 * @description: 缓存同步 --- redis pub/sub
 */
public class RedisCacheMessageMulticaster implements CacheMessageMulticaster {

    private L2CacheConfigProperties properties;

    private RedisTemplate redisTemplate;

    private RedisMessageListenerContainer container;

    private String topic;

    private MessageListener listener;

    public RedisCacheMessageMulticaster(L2CacheConfigProperties properties,
                                        RedisTemplate redisTemplate,
                                        RedisMessageListenerContainer container) {
        this.properties = properties;
        this.redisTemplate = redisTemplate;
        this.container = container;
        this.topic = Objects.requireNonNull(properties.getSyncTopic());
    }

    @Override
    public void multicast(CacheMessage message) {
        Long clients = redisTemplate.convertAndSend(topic, message);
    }

    @Override
    public void addMessageListener(MessageListener listener) {
        this.listener = listener;
        container.addMessageListener((Message message, byte[] pattern) -> {
                    CacheMessage msg = (CacheMessage) redisTemplate.getValueSerializer().deserialize(message.getBody());
                    listener.onMessage(msg);
                }
                , new ChannelTopic(this.topic));

    }


}
